// crop.js
Page({
  data: {
    imageUrl: '',
    croppedImageUrl: '',
    cropMode: 'free', // 'free' or 'ratio'
    aspectRatio: '1:1',
    formatIndex: 0,
    formats: ['JPEG', 'PNG', 'WebP'],
    
    // 图片原始尺寸
    originalWidth: 0,
    originalHeight: 0,
    
    // 裁剪参数
    cropX: 0,
    cropY: 0,
    cropWidth: 200,
    cropHeight: 200,
    
    // 最大值限制
    maxCropX: 0,
    maxCropY: 0,
    maxCropWidth: 0,
    maxCropHeight: 0,
    
    // 预览画布尺寸
    previewCanvasWidth: 200,
    previewCanvasHeight: 200,
    
    // 裁剪结果信息
    croppedWidth: 0,
    croppedHeight: 0,
    
    cropping: false
  },

  onLoad() {
    console.log('裁剪页面加载');
  },

  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({
          imageUrl: tempFilePath,
          croppedImageUrl: ''
        });
        
        // 获取图片信息并初始化裁剪参数
        this.initCropParams(tempFilePath);
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
        wx.showToast({
          title: '选择图片失败',
          icon: 'error'
        });
      }
    });
  },

  initCropParams(imagePath) {
    wx.getImageInfo({
      src: imagePath,
      success: (res) => {
        const { width, height } = res;
        const cropSize = Math.min(width, height, 300);
        
        this.setData({
          originalWidth: width,
          originalHeight: height,
          cropX: Math.floor((width - cropSize) / 2),
          cropY: Math.floor((height - cropSize) / 2),
          cropWidth: cropSize,
          cropHeight: cropSize,
          maxCropX: width - 50,
          maxCropY: height - 50,
          maxCropWidth: width,
          maxCropHeight: height
        });
        
        this.updatePreview();
      },
      fail: (err) => {
        console.error('获取图片信息失败:', err);
        wx.showToast({
          title: '获取图片信息失败',
          icon: 'error'
        });
      }
    });
  },

  selectCropMode(e) {
    const mode = e.currentTarget.dataset.mode;
    this.setData({ cropMode: mode });
    
    if (mode === 'ratio') {
      this.applyAspectRatio();
    }
  },

  selectAspectRatio(e) {
    const ratio = e.currentTarget.dataset.ratio;
    this.setData({ aspectRatio: ratio });
    this.applyAspectRatio();
  },

  applyAspectRatio() {
    const [widthRatio, heightRatio] = this.data.aspectRatio.split(':').map(Number);
    const maxWidth = this.data.originalWidth - this.data.cropX;
    const maxHeight = this.data.originalHeight - this.data.cropY;
    
    let newWidth, newHeight;
    
    if (maxWidth / widthRatio < maxHeight / heightRatio) {
      newWidth = maxWidth;
      newHeight = (maxWidth / widthRatio) * heightRatio;
    } else {
      newHeight = maxHeight;
      newWidth = (maxHeight / heightRatio) * widthRatio;
    }
    
    this.setData({
      cropWidth: Math.floor(newWidth),
      cropHeight: Math.floor(newHeight)
    });
    
    this.updatePreview();
  },

  onCropXChange(e) {
    const cropX = e.detail.value;
    this.setData({ 
      cropX,
      maxCropWidth: this.data.originalWidth - cropX
    });
    this.updatePreview();
  },

  onCropYChange(e) {
    const cropY = e.detail.value;
    this.setData({ 
      cropY,
      maxCropHeight: this.data.originalHeight - cropY
    });
    this.updatePreview();
  },

  onCropWidthChange(e) {
    let cropWidth = e.detail.value;
    
    if (this.data.cropMode === 'ratio') {
      const [widthRatio, heightRatio] = this.data.aspectRatio.split(':').map(Number);
      const cropHeight = (cropWidth / widthRatio) * heightRatio;
      this.setData({ cropWidth, cropHeight });
    } else {
      this.setData({ cropWidth });
    }
    
    this.updatePreview();
  },

  onCropHeightChange(e) {
    let cropHeight = e.detail.value;
    
    if (this.data.cropMode === 'ratio') {
      const [widthRatio, heightRatio] = this.data.aspectRatio.split(':').map(Number);
      const cropWidth = (cropHeight / heightRatio) * widthRatio;
      this.setData({ cropWidth, cropHeight });
    } else {
      this.setData({ cropHeight });
    }
    
    this.updatePreview();
  },

  onFormatChange(e) {
    this.setData({
      formatIndex: e.detail.value
    });
  },

  updatePreview() {
    if (!this.data.imageUrl) return;
    
    const canvas = wx.createCanvasContext('cropPreviewCanvas', this);
    const { cropX, cropY, cropWidth, cropHeight } = this.data;
    
    // 计算预览画布尺寸
    const maxPreviewSize = 200;
    const scale = Math.min(maxPreviewSize / cropWidth, maxPreviewSize / cropHeight);
    const previewWidth = cropWidth * scale;
    const previewHeight = cropHeight * scale;
    
    this.setData({
      previewCanvasWidth: previewWidth,
      previewCanvasHeight: previewHeight
    });
    
    // 绘制裁剪预览
    canvas.drawImage(
      this.data.imageUrl,
      cropX, cropY, cropWidth, cropHeight,
      0, 0, previewWidth, previewHeight
    );
    
    canvas.draw();
  },

  cropImage() {
    if (!this.data.imageUrl) {
      wx.showToast({
        title: '请先选择图片',
        icon: 'error'
      });
      return;
    }

    this.setData({ cropping: true });

    const canvas = wx.createCanvasContext('cropCanvas', this);
    const { cropX, cropY, cropWidth, cropHeight } = this.data;
    
    // 绘制裁剪后的图片
    canvas.drawImage(
      this.data.imageUrl,
      cropX, cropY, cropWidth, cropHeight,
      0, 0, cropWidth, cropHeight
    );
    
    canvas.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: 'cropCanvas',
        x: 0,
        y: 0,
        width: cropWidth,
        height: cropHeight,
        fileType: this.data.formats[this.data.formatIndex].toLowerCase(),
        success: (res) => {
          this.setData({
            croppedImageUrl: res.tempFilePath,
            croppedWidth: cropWidth,
            croppedHeight: cropHeight,
            cropping: false
          });
          
          wx.showToast({
            title: '裁剪完成',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('裁剪失败:', err);
          this.setData({ cropping: false });
          wx.showToast({
            title: '裁剪失败',
            icon: 'error'
          });
        }
      });
    });
  },

  resetCrop() {
    if (this.data.originalWidth && this.data.originalHeight) {
      const cropSize = Math.min(this.data.originalWidth, this.data.originalHeight, 300);
      
      this.setData({
        cropX: Math.floor((this.data.originalWidth - cropSize) / 2),
        cropY: Math.floor((this.data.originalHeight - cropSize) / 2),
        cropWidth: cropSize,
        cropHeight: cropSize
      });
      
      this.updatePreview();
    }
  },

  saveImage() {
    if (!this.data.croppedImageUrl) {
      wx.showToast({
        title: '没有可保存的图片',
        icon: 'error'
      });
      return;
    }

    wx.saveImageToPhotosAlbum({
      filePath: this.data.croppedImageUrl,
      success: () => {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        if (err.errMsg.includes('auth deny')) {
          wx.showModal({
            title: '提示',
            content: '需要授权访问相册才能保存图片',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting();
              }
            }
          });
        } else {
          wx.showToast({
            title: '保存失败',
            icon: 'error'
          });
        }
      }
    });
  }
})